package com.alm.token.ui.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alm.token.ConStant;
import com.alm.token.MyApp;
import com.alm.token.R;
import com.alm.token.base.BaseActivity;
import com.alm.token.ui.data.bean.AddAppendOrderData;
import com.alm.token.ui.data.bean.G12CanData;
import com.alm.token.ui.data.bean.ShowUserXingjiData;
import com.alm.token.ui.data.bean.UserListLHData;
import com.alm.token.ui.data.bean.UserWalletData;
import com.alm.token.ui.persenter.MyPreenter;
import com.alm.token.ui.view.QuantitativeOrderOpenAddView;
import com.alm.token.utils.ActionBarHelper;
import com.alm.token.utils.CommonUtil;
import com.alm.token.utils.LogUtil;
import com.haozhang.lib.SlantedTextView;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import baibeiwallet.Constant;
import baibeiwallet.utils.DialogUtils;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class QuantitativeOrderCloseActivity extends BaseActivity implements QuantitativeOrderOpenAddView<Object>, TextWatcher {
    @BindView(R.id.leftItem)
    ImageView leftItem;
    @BindView(R.id.centerItem)
    TextView centerItem;
    @BindView(R.id.rightItem)
    TextView rightItem;
    @BindView(R.id.img_ordertype)
    SlantedTextView imgOrdertype;
    @BindView(R.id.tv_orderid)
    TextView tvOrderid;
    @BindView(R.id.tv_shuliang)
    TextView tvShuliang;
    @BindView(R.id.tv_shuliang2)
    TextView tvShuliang2;
    @BindView(R.id.tv_yaoqingma)
    TextView tvYaoqingma;
    @BindView(R.id.tv_lejiday)
    TextView tvLejiday;
    @BindView(R.id.tv_start)
    TextView tvStart;
    @BindView(R.id.tv_end)
    TextView tvEnd;
    @BindView(R.id.tv_yuji)
    TextView tvYuji;
    @BindView(R.id.tv_leji)
    TextView tvLeji;
    @BindView(R.id.close_btn)
    TextView closeBtn;
    @BindView(R.id.tv_uservipname)
    TextView tvUservipname;
    @BindView(R.id.tv_closeexpendblv)
    TextView tvCloseexpendblv;
    @BindView(R.id.tv_closemoney)
    TextView tvClosemoney;

    private UserListLHData.DataBean dataBean;
    public static int closeOrderSucc = 3;
    private double guanbibilv = 0d;

    //    private List<String> zhouqi = new ArrayList<>();
//    private List<String> yuehua = new ArrayList<>();
    private List<String> dataBeanBizhong = new ArrayList<>();
    private List<Double> dataBeanCanClosemoney = new ArrayList<>();
    private List<String> bizhong = new ArrayList<>();
    private List<String> bizhongid = new ArrayList<>();
    //    private List<String> keyong = new ArrayList<>();
    private List<String> jine = new ArrayList<>();
    private List<String> xingji = new ArrayList<>();
    private List<String> bilv = new ArrayList<>();
    private int bizhongType = 0;
    private double totalMoney = 0.00d, number = 0.00d;
    private String biId = "1", bibilv = "0.00";
    @BindView(R.id.tv_bizhongshow)
    TextView tvBizhongshow;
    @BindView(R.id.tv_bizhongshow2)
    TextView tvBizhongshow2;
    @BindView(R.id.tv_keyong)
    TextView tvKeyong;
    @BindView(R.id.edt_inputnumber)
    EditText edtInputnumber;
    @BindView(R.id.tv_bilv)
    TextView tvBilv;
    @BindView(R.id.rly_bizhongselect)
    RelativeLayout rlyBizhongSelect;
    @BindView(R.id.tv_appendbilvmath)
    TextView tvAppendbilvmath;
    @BindView(R.id.tv_totalbilvmath)
    TextView tvTotalbilvmath;
    @BindView(R.id.ly_xinjibody)
    LinearLayout lyXxinjiBody;

    @BindView(R.id.ly_canselect)
    LinearLayout lyCanselect;
    @BindView(R.id.close_btn1)
    TextView tvclose_btn1;


    @Override
    protected MyPreenter initPreenter() {
        return new MyPreenter(this);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_quantitative_order_close;
    }

    @Override
    protected void initVariables() {
        dataBean = (UserListLHData.DataBean) getIntent().getSerializableExtra("databean");
    }

    @Override
    protected void initViews() {
        new ActionBarHelper(this)
                .setTitle(getString(R.string.title_hint_item29))
                .setRightIcon(R.drawable.lh_order, this);

        tvOrderid.setText(dataBean.getOrderid());
        DecimalFormat dec = new DecimalFormat("0.0000");

        StringBuffer shuliang1 = new StringBuffer();
        if (dataBean.getBizhong() != null && dataBean.getBizhong().size() != 0) {
            dataBeanBizhong = dataBean.getBizhong();
            dataBeanCanClosemoney = dataBean.getBizhongMoney();
            for (int i = 0; i < dataBean.getBizhong().size(); i++) {
                shuliang1.append(dec.format(dataBean.getBizhongMoney().get(i)) + " " + dataBean.getBizhong().get(i) + (i == dataBean.getBizhong().size() - 1 ? "" : i % 2 == 1 ? "\n" : "/"));
            }
        } else {
            lyCanselect.setVisibility(View.GONE);
            tvclose_btn1.setVisibility(View.GONE);
            shuliang1.append(dec.format(0) + " ETH");
        }
        String shuliang2 = dataBean.getBizhong1() + " " + dec.format(dataBean.getBizhongMoney1());
        tvShuliang.setText(shuliang1.toString());
        tvShuliang2.setText(shuliang2);
//        tvShuliang.setText(dec.format(Double.parseDouble(dataBean.getShuliang().isEmpty() ? "0" : dataBean.getShuliang())));
//        tvYaoqingma.setText("  开启数量" + dataBean.getYaoqingma());
        tvLejiday.setText(dataBean.getLejiday().replace("-", "") + "Days");
        tvStart.setText("Start: " + CommonUtil.getDateTimeFromMillisecond(Long.parseLong(dataBean.getStart())).split(" ")[0]);

        if (dataBean.getEnd() != null && Long.parseLong(dataBean.getEnd()) != 0 && Integer.parseInt(dataBean.getOrderStatus()) != 0) {
//            tvEnd.setVisibility(View.VISIBLE);
//            tvEnd.setText("结束时间:" + CommonUtil.getDateTimeFromMillisecond(Long.parseLong(dataBean.getEnd())).split(" ")[0]);
            tvYuji.setText("End: " + CommonUtil.getDateTimeFromMillisecond(Long.parseLong(dataBean.getYuji())).split(" ")[0]);
        } else {
            tvYuji.setText("Expire: " + CommonUtil.getDateTimeFromMillisecond(Long.parseLong(dataBean.getYuji())).split(" ")[0]);

//            tvEnd.setVisibility(View.GONE);
        }

//        if (dataBean.getEnd() != null && Long.parseLong(dataBean.getEnd()) != 0 && Integer.parseInt(dataBean.getOrderStatus()) != 1) {
//            tvEnd.setVisibility(View.VISIBLE);
//            tvEnd.setText("结束时间:" + CommonUtil.getDateTimeFromMillisecond(Long.parseLong(dataBean.getEnd())).split(" ")[0]);
//        } else {
//            tvEnd.setVisibility(View.GONE);
//        }

//        tvYuji.setText("预计时间:" + CommonUtil.getDateTimeFromMillisecond(Long.parseLong(dataBean.getYuji())).split(" ")[0]);
        DecimalFormat dec1 = new DecimalFormat("0.00");
        tvLeji.setText("Total：" + dec1.format(Double.parseDouble(dataBean.getLeji().isEmpty() ? "0" : dataBean.getLeji())));

        if (Integer.parseInt(dataBean.getOrderStatus()) != 0) {
//            imgOrdertype.setImageDrawable(getResources().getDrawable(R.drawable.guanbi1));
            imgOrdertype.setText(getString(R.string.alphago_hint_ygb))
                    .setTextColor(getResources().getColor(R.color.quanlitative_flag3))
                    .setSlantedBackgroundColor(getResources().getColor(R.color.quanlitative_flag2))
                    .setTextSize(11)
                    .setSlantedLength(55)
                    .setMode(SlantedTextView.MODE_RIGHT_TRIANGLE);
        } else {
//            imgOrdertype.setImageDrawable(getResources().getDrawable(R.drawable.jingx));
            imgOrdertype.setText(getString(R.string.alphago_hint_jxz))
                    .setTextColor(Color.WHITE)
                    .setSlantedBackgroundColor(getResources().getColor(R.color.quanlitative_flag1))
                    .setTextSize(11)
                    .setSlantedLength(55)
                    .setMode(SlantedTextView.MODE_RIGHT_TRIANGLE);
        }

        tvUservipname.setText(dataBean.getNowshenfen());
        tvCloseexpendblv.setText(dataBean.getGuanbibili());
//        guanbibilv=Double.parseDouble(dataBean.getGuanbibili().split("%")[0]);
        tvClosemoney.setText(dataBean.getGuanbikouchu() + "ETH");

//        if (MyApp.getUserData() != null && MyApp.getUserData().getData() != null && MyApp.getUserData().getData().getVipOrder() != null) {
//            tvUservipname.setText(MyApp.getUserData().getData().getVipOrder().getVipName());
//        } else {
//            tvUservipname.setText("普通会员");
//        }
//        tvCloseexpendblv;
//        tvClosemoney;
    }


    @Override
    protected void loadData() {
        preenter.getShowUserXingjiData();
    }

    @Override
    public void onClick(View v) {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.close_btn, R.id.rightItem, R.id.rly_bizhongselect, R.id.close_btn1})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.close_btn:
//                showToast(closeBtn.getText().toString());
                if (tvclose_btn1.getVisibility() == View.GONE) {
                    if (dataBean != null) {

                        UserWalletData.DataBean.SysMsgBean sysMsgBean = new UserWalletData.DataBean.SysMsgBean();
                        sysMsgBean.setTitle(getString(R.string.alphago_hint_warn9));
                        sysMsgBean.setContent(getString(R.string.alphago_hint_warn10));
                        DialogUtils.showInfor1(this, sysMsgBean, (pwd) -> {

                            DialogUtils.enterPayPsw(this, (pwd1) -> {
                                preenter.getCloseOrderData(dataBean.getOrderid() + "", pwd1);
                            });


                        });
//                    preenter.getCloseOrderData(dataBean.getOrderid() + "");
                    }
                    break;
                }
                if (number == 0) {
                    showToast(getString(R.string.alphago_hint_warn5));
                    break;
                }
                if (dataBean != null) {

                    UserWalletData.DataBean.SysMsgBean sysMsgBean = new UserWalletData.DataBean.SysMsgBean();
                    sysMsgBean.setTitle(getString(R.string.alphago_hint_warn9));
                    sysMsgBean.setContent(getString(R.string.alphago_hint_warn12, CommonUtil.saveToPoint4WithNo(number), tvBizhongshow.getText().toString()));
                    DialogUtils.showInfor1(this, sysMsgBean, (pwd) -> {

                        DialogUtils.enterPayPsw(this, (pwd1) -> {
                            preenter.getcloseOrderPartData(dataBean.getOrderid() + "", biId, String.valueOf(number), pwd1);
                        });


                    });
//                    preenter.getCloseOrderData(dataBean.getOrderid() + "");
                }

                break;
            case R.id.rightItem:
                startActivity(LH2OrderHistoryActivity.class);
                break;
            case R.id.rly_bizhongselect:
//                showToast("选择币种");
//                if (bizhong != null && bizhong.size() != 1) {
//                    showPopupMenu(rlyBizhongSelect);
//                }
                if (dataBeanBizhong != null)
                    showPopupMenu(rlyBizhongSelect);
                break;
            case R.id.close_btn1:
//                if(lyCanselect.getVisibility()==View.VISIBLE){
//                    tvclose_btn1.setText("");
//                }else {
//                    lyCanselect.setVisibility(View.VISIBLE);
//                }
                if (dataBean != null) {

                    UserWalletData.DataBean.SysMsgBean sysMsgBean = new UserWalletData.DataBean.SysMsgBean();
                    sysMsgBean.setTitle(getString(R.string.alphago_hint_warn9));
                    sysMsgBean.setContent(getString(R.string.alphago_hint_warn10));
                    DialogUtils.showInfor1(this, sysMsgBean, (pwd) -> {

                        DialogUtils.enterPayPsw(this, (pwd1) -> {
                            preenter.getCloseOrderData(dataBean.getOrderid() + "", pwd1);
                        });


                    });
//                    preenter.getCloseOrderData(dataBean.getOrderid() + "");
                }
                break;
        }
    }

    @Override
    public void getShowUserXingjiData(Object o) {
        if (o instanceof ShowUserXingjiData) {
            ShowUserXingjiData data = (ShowUserXingjiData) o;
//            showToast(data.getMsg());
            if (data.getStatus() != 0)
                showToast(data.getMsg());
            if (data.getData() != null) {//设置可输入
                ShowUserXingjiData.DataBean dataBean = data.getData();
//                zhouqi.addAll(dataBean.getZhouqi());
//                yuehua.addAll(dataBean.getYuehua());
                bizhong.addAll(dataBean.getBizhong());
                bizhongid.addAll(dataBean.getBizhongid());
//                keyong.addAll(dataBean.getKeyong());
                jine.addAll(dataBean.getJine());
                xingji.addAll(dataBean.getXingji());
                bilv.addAll(dataBean.getBilv());

                if (dataBeanBizhong != null) {
                    for (int i = 0; i < dataBeanBizhong.size(); i++) {

                        for (int j = 0; j < bizhong.size(); j++) {
                            if (dataBeanBizhong.get(i).equalsIgnoreCase(bizhong.get(j))) {
                                totalMoney = totalMoney + this.dataBean.getBizhongMoney().get(i) * Double.parseDouble(bilv.get(j));
                                break;
                            }
                        }
                    }
                    for (int j = 0; j < bizhong.size(); j++) {
                        if (this.dataBean.getBizhong1().equalsIgnoreCase(bizhong.get(j))) {
                            totalMoney = totalMoney + this.dataBean.getBizhongMoney1() * Double.parseDouble(bilv.get(j));
                            break;
                        }
                    }

                    bizhongType = 0;
                    initView();
                }
                mathNumber(number);
                edtInputnumber.setText("");
                edtInputnumber.addTextChangedListener(this);

            }
        }
    }

    DecimalFormat dec1;
    private int ll1 = -1;
    private int xin = 0;
    private double closemoney = 0.00d;

    private void mathNumber(double number) {
        dec1 = new DecimalFormat("0.0000");
        closemoney = number * Double.parseDouble(bibilv);
        tvAppendbilvmath.setText("≈$" + dec1.format(closemoney));

        if (closemoney == 0) {
            tvTotalbilvmath.setText("≈$" + dec1.format(totalMoney));
        } else {
            tvTotalbilvmath.setText("≈$" + dec1.format(totalMoney - closemoney));
        }

        BigDecimal b1 = new BigDecimal(totalMoney - closemoney);
        double money1 = b1.setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue();

        LogUtil.e("money1=" + money1);
        if (jine != null && jine.size() != 0) {
            for (int i = 0; i < jine.size(); i++) {
                //"jine":["500.0","2000.0","5000.0","10000.0"]
//                if (number < Double.parseDouble(jine.get(i) != null ? jine.get(i) : "0")) {
                if (money1 < Double.parseDouble(jine.get(i) != null ? jine.get(i) : "0")) {
                    ll1 = i;//2
                    LogUtil.e("ll1_1=" + ll1);
                    break;
                } else {
                    ll1 = jine.size();
                    LogUtil.e("ll1_2=" + ll1);
                }
            }
        }//0无效 1 2 3 4 有效
        xin = ll1;
        if (ll1 == 0) {
            ll1++;
        }
        LogUtil.e("ll1_3=" + ll1);//2
        if (ll1 <= lyXxinjiBody.getChildCount()) {
            for (int i = 0; i < lyXxinjiBody.getChildCount(); i++) {//4number  i=0-3
                if (i < ll1) { //i=0 1 2 3  ll1=1 2 3 4
                    lyXxinjiBody.getChildAt(i).setVisibility(View.VISIBLE);
                } else {
                    lyXxinjiBody.getChildAt(i).setVisibility(View.GONE);
                }
            }
        }
    }

    private void initView() {
        tvBizhongshow.setText(dataBeanBizhong.get(bizhongType));
        tvBizhongshow2.setText(dataBeanBizhong.get(bizhongType));
        if (dataBeanCanClosemoney != null && dataBeanCanClosemoney.size() != 0) {
            tvKeyong.setText(CommonUtil.saveToPoint4WithNo(dataBeanCanClosemoney.get(bizhongType)));
        }
        if (bilv != null && bilv.size() != 0) {
            for (int j = 0; j < bizhong.size(); j++) {
                if (dataBeanBizhong.get(bizhongType).equalsIgnoreCase(bizhong.get(j))) {
                    tvBilv.setText("≈" + bilv.get(j) + "USD/" + bizhong.get(j));
                    biId = bizhongid.get(j);
                    bibilv = bilv.get(j);
                    break;
                }
            }
        }
        edtInputnumber.setText("");
    }

    @Override
    public void getAddLhOrderData(Object o) {

    }

    @Override
    public void getAppendOrderData(Object o) {

    }

    @Override
    public void getCloseOrderData(Object o) {

        if (o instanceof AddAppendOrderData) {
            AddAppendOrderData data = (AddAppendOrderData) o;
            showToast(data.getMsg());
            if (data.getStatus() == 0) {
                setResult(closeOrderSucc);
                finish();
            }
        }

    }

    @Override
    public void getZhuijiashowData(Object o) {

    }

    @Override
    public void getUserListLHData(Object o) {

    }

    @Override
    public void getG12CanData(G12CanData g12CanData) {

    }

    @Override
    public void getData(Object o) {

    }

    @Override
    public void jumpToLoginAct(int staue) {
        if (staue == 3) {
//            showToast(getString(R.string.common_relogin));
//            Intent intent = new Intent();
//            intent.setAction(ConStant.EXIT_APP);
//            sendBroadcast(intent);
//            startActivity(BlockWalletLoginActivity.class);
//            finish();
        } else if (staue == 4) {
//            showToast(getString(R.string.paypasw_hint_setpaypsw));
//            Intent intent = new Intent(getActivity(),PayPwdActivity.class);
//            intent.putExtra("PayPwdActivityType",PayPwdActivity.PAYPSW_SET);
//            startActivity(intent);
//            getActivity().finish();
            showToSetPaypswDialog();
        } else if (staue == 666) {
            showToUpdata();
        }
    }

    @Override
    public void onError(String error) {
        showToast(getString(R.string.common_loaderrritry));
    }

    @Override
    public void ShowProgress() {
        showWaitDialog();

    }

    @Override
    public void hideProgress() {
        hideWaitDialog();

    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (s.toString().contains(".")) {
            if (s.length() - 1 - s.toString().indexOf(".") > 4) {
                s = s.toString().subSequence(0, s.toString().indexOf(".") + 5);
                edtInputnumber.setText(s);
                edtInputnumber.setSelection(s.length());
            }
        }
        if (s.toString().trim().substring(0).equals(".")) {
            s = "0" + s;
            edtInputnumber.setText(s);
            edtInputnumber.setSelection(2);
        }

        if (s.toString().startsWith("0")
                && s.toString().trim().length() > 1) {
            if (!s.toString().substring(1, 2).equals(".")) {
                edtInputnumber.setText(s.subSequence(0, 1));
                edtInputnumber.setSelection(1);
                return;
            }
        }
        number = Double.parseDouble(s != null ? (!s.toString().isEmpty() ? s.toString() : "0") : "0");
        if (number > Double.parseDouble(tvKeyong.getText().toString().isEmpty() ? "0" : tvKeyong.getText().toString())) {
            showToast(getString(R.string.conversioncurrency_hint1_warn6));
            number = Double.parseDouble(tvKeyong.getText().toString().isEmpty() ? "0" : tvKeyong.getText().toString());
            edtInputnumber.setText(CommonUtil.saveToPoint4WithNo(number) + "");
        }
        mathNumber(number);
    }

    @Override
    public void afterTextChanged(Editable s) {

    }


    public void showPopupMenu(View view) {
        //参数View 是设置当前菜单显示的相对于View组件位置，具体位置系统会处理
        PopupMenu popupMenu = new PopupMenu(this, view);
        //加载menu布局
        Menu menu = popupMenu.getMenu();
        for (String bi : dataBeanBizhong) {
            if (!bi.equalsIgnoreCase(Constant.G12ContractName)) {
                menu.add(bi);
            }
        }
        popupMenu.getMenuInflater().inflate(R.menu.menu_popmenu, menu);


        //设置menu中的item点击事件
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {

                for (int i = 0; i < bizhong.size(); i++) {
                    if (item.getTitle().toString().equalsIgnoreCase(dataBeanBizhong.get(i))) {
                        if (item.getTitle().toString().equalsIgnoreCase(Constant.G12ContractName)) {
                            showToast(getString(R.string.crowdfund_hint_warn4));
                            break;
                        }
                        bizhongType = i;
                        initView();
                        mathNumber(number);
                        break;
                    }
                }
                return true;
            }
        });
        popupMenu.show();
    }
}
